package com.m1.tzolkin.model.util.board;

import java.util.Collection;

import com.m1.tzolkin.model.exceptions.EndOfGameException;
import com.m1.tzolkin.model.exceptions.NoMovedWorkersException;
import com.m1.tzolkin.model.exceptions.WaitingOperationsException;
import com.m1.tzolkin.model.util.ITurnsCounter;
import com.m1.tzolkin.model.util.player.IPlayer;


public class TimedBoard<E extends IPlayer, C extends ITurnsCounter> extends Board<E> implements ITimedBoard<E, C> {

	// ATTRIBUTS
	
	/**
	 * 
	 */
	private static final long serialVersionUID = -6054347987252113315L;
	private final C turnsCounter;
	private int turn;
	
	// CONSTRUCTEUR
	
	public TimedBoard(Collection<E> players, C c) {
		super(players);
		if (c == null) {
			throw new IllegalArgumentException();
		}
		turnsCounter = c;
		turn = 0;
	}
	
	// REQUETES
	
	@Override
	public int getTurn() {
		return turnsCounter.getTurn();
	}
	
	@Override
	public int getActualTurn() {
		return turnsCounter.getTurn() * getPlayers().size() + getPlayers().indexOf(getCurrentPlayer()) - getPlayers().indexOf(getFirstPlayer());
	}
	
	@Override
	public boolean isFinished() {
		return turnsCounter.getTurn() >= turnsCounter.getTurns();
	}
	
	/**
	 * Retourne le calendrier associ� � ce plateau.
	 */
	protected C getTurnsCounter() {
		return turnsCounter;
	}
	
	// COMMANDES
	
	@Override
	public E endTurn() throws WaitingOperationsException, EndOfGameException, NoMovedWorkersException {
		E player = super.endTurn();
		if (turn == getPlayers().size() - 1) {
			turnsCounter.incTurn();
			turn = 0;
		} else {
			++turn;
		}
		return player;
	}

}
